package com.duoqin.syncassistant.ui;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.duoqin.account.data.RefreshTokenResponse;
import com.duoqin.account.DuoqinAccount;
import com.duoqin.account.ui.AccountActivity;
import com.duoqin.account.viewmodel.LoginViewModel;
import com.duoqin.common.ui.AbsActivity;
import com.duoqin.syncassistant.R;
import com.duoqin.syncassistant.SyncAssistantApplication;
import com.duoqin.syncassistant.viewmodel.AppViewModel;
import com.duoqin.syncassistant.viewmodel.BaseViewModel;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AbsActivity {

    private LoginViewModel mViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupTitle(getString(R.string.app_name));

        findViewById(R.id.sync_assistant).setOnClickListener(this);
        findViewById(R.id.remote_add_contacts).setOnClickListener(this);

        setupModelObserver();
        if (SyncAssistantApplication.getsInstance().hasLogin()) {
            mViewModel.refreshToken(DuoqinAccount.getAccountToken(getApplicationContext()));
        }
        checkPermissions();
    }

    @Override
    public void onClick(View v) {
        if (R.id.sync_assistant == v.getId()) {
            Intent intent = new Intent(this, SyncAssistantActivity.class);
            startActivity(intent);
        } else if (R.id.remote_add_contacts == v.getId()) {
            Intent intent = new Intent(this, RemoteAddContactsActivity.class);
            startActivity(intent);
        } else {
            super.onClick(v);
        }
    }

    private void setupModelObserver() {
        mViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

        final Observer<RefreshTokenResponse> refreshTokenResponseObserver =
                new Observer<RefreshTokenResponse>() {
                    @Override
                    public void onChanged(@Nullable final RefreshTokenResponse response) {
                        Log.i(TAG, "onChanged RefreshTokenResponse = " + response);
                        if (response != null) {
                            Log.d(TAG, "onChanged code = " + response.getCode()
                                    + "; msg = " + response.getMsg());
                            Log.d(TAG, "onChanged data = " + response.getData());
                        }
                        if (response != null) {
                            if (BaseViewModel.SERVER_RESULT_SUCCESS == response.getCode()) {
                                if (response.getData() != null) {
                                    SyncAssistantApplication.getsInstance().updateToken(
                                            response.getData().getAccessToken(),
                                            response.getData().getExpiredAt());
                                }
                            } else if (BaseViewModel.SERVER_RESULT_ERROR_INVALID_TOKEN
                                    == response.getCode()) {
                                Toast.makeText(getApplicationContext(),
                                        R.string.error_login_token_expired,
                                        Toast.LENGTH_SHORT).show();
                                SyncAssistantApplication.getsInstance().clearToken();
                            }
                        } else {
                            Log.w(TAG, "refresh token failed");
                        }
                    }
                };
        mViewModel.reFreshTokenResponse().observe(this, refreshTokenResponseObserver);

        // Get QRCode
        AppViewModel mAppViewModel = ViewModelProviders.of(this).get(AppViewModel.class);
        mAppViewModel.appQRCodeResponse();
        mAppViewModel.getAppQRCode();
    }

    private boolean checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionsNeeded = new ArrayList<String>();
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(Manifest.permission.GET_ACCOUNTS);
            }
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(Manifest.permission.READ_CONTACTS);
            }
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(Manifest.permission.READ_SMS);
            }

            if (permissionsNeeded.size() > 0) {
                requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]),
                        PERMISSIONS_REQUEST_CODE);
            }
            return permissionsNeeded.size() > 0;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PERMISSIONS_REQUEST_CODE != requestCode) {
            return;
        }
        if (permissions.length > 0) {
            for (int permissionId = 0; permissionId < permissions.length; permissionId++) {
                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[permissionId])) {
                    if (grantResults.length > permissionId) {
                        if (0 != grantResults[permissionId]) {
                            finish();
                        }
                    }
                }
            }
        }
    }
}
